package com.graduation.smartparkingplatform.Controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.graduation.smartparkingplatform.Response.Response;
import com.graduation.smartparkingplatform.Response.ResponseUtils;
import com.graduation.smartparkingplatform.Service.PayService;
import com.graduation.smartparkingplatform.Utils.AlipayBean;
import com.graduation.smartparkingplatform.Utils.RandomOutTradeNo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/pay")
public class PayController {

  @Autowired private PayService payService;

  @Value("${aliPay.publicKey}")
  private String publicKey;

  @Value("${aliPay.charset}")
  private String charset;

  @Value("${aliPay.signType}")
  private String signType;

  // 调用支付宝支付
  @GetMapping("/alipay")
  public String alipay(
      @RequestParam("totalAmount") String totalAmount, @RequestParam("body") String body)
      throws AlipayApiException {
    // 随机生成订单号
    String outTradeNo = RandomOutTradeNo.getOutTradeNo();
    String subject = "智慧停车场费用" + outTradeNo.substring(4, 10);
    String productCode = "FAST_INSTANT_TRADE_PAY";
    AlipayBean alipayBean = new AlipayBean();
    alipayBean.setOut_trade_no(outTradeNo);
    alipayBean.setSubject(subject);
    alipayBean.setTotal_amount(totalAmount);
    alipayBean.setBody(body);
    Boolean aliPay_record =
        payService.aliPay_record(outTradeNo, productCode, subject, totalAmount, body);
    return payService.aliPay(alipayBean);
  }

  // 支付成功, 进入同步通知接口
  @RequestMapping("/alipayReturnNotice")
  public Response alipayReturnNotice(HttpServletRequest request, HttpServletRequest response)
      throws Exception {
    // 获取支付宝GET过来反馈信息
    Map<String, String> params = new HashMap<String, String>();
    Map<String, String[]> requestParams = request.getParameterMap();
    for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
      String name = (String) iter.next();
      String[] values = (String[]) requestParams.get(name);
      String valueStr = "";
      for (int i = 0; i < values.length; i++) {
        valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
      }
      // 乱码解决，这段代码在出现乱码时使用
      valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
      params.put(name, valueStr);
    }

    boolean signVerified = AlipaySignature.rsaCheckV1(params, publicKey, charset, signType);

    if (signVerified) {
      // 商户订单号
      String outTradeNo =
          new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

      Boolean aliPay_record = payService.aliPay_record_change(outTradeNo);
      if (aliPay_record) {
        return ResponseUtils.buildSuccess("支付成功");
      }
      return ResponseUtils.buildSYSTEM_ERROR("支付失败");
    }
    return ResponseUtils.buildSYSTEM_ERROR("支付校验失败");
  }

  // 判断支付是否成功
  @GetMapping("/alipayStatus")
  public Response alipayStatus(@RequestParam("out_trade_no") String outTradeNo) {
    Boolean alipayStatus = payService.alipayStatus(outTradeNo);
    if (alipayStatus) {
      return ResponseUtils.buildSuccess("支付成功");
    }
    return ResponseUtils.buildSuccess("暂未支付");
  }
}
